import { useUserStore } from '@st/modules/login/stores/user'

const permissionFlg = import.meta.env.VITE_APP_PLUGINS.includes('permission')

export default (app: any) => {
  /**
   * 按钮权限控制指令
   * @author wangyuan
   */
  app.directive('permission', {
    mounted(el: any, bind: any) {
      if (permissionFlg) {
        const userStore = useUserStore()
        let buttons = userStore.userInfo.buttons
        let val = bind.value
        let hasPremission = false
        buttons.forEach((v: any) => {
          if (v.routeName === val) {
            hasPremission = true
          }
        })

        if (!hasPremission) {
          el.remove()
        }
      }
    }
  })

  /**
   * 按钮权限控制指令 - or
   * @author wangyuan
   */
  app.directive('permission-or', {
    mounted(el: any, bind: any) {
      if (permissionFlg) {
        const userStore = useUserStore()
        let buttons = userStore.userInfo.buttons
        let vals = bind.value
        let hasPremission = false
        vals.forEach((v: any) => {
          if (buttons.filter((item: any) => item.routeName === v)?.length) {
            hasPremission = true
          }
        })

        if (!hasPremission) {
          el?.remove()
        }
      }
    }
  })
}
